#include "WS2812B.h"

/*宏定义*/
#define LED_PIN 5
#define NUM_LEDS 30
#define LED_TYPE WS2812
#define COLOR_ORDER GRB

/*静态全局变量*/
static CRGB leds[NUM_LEDS];//光带leds
static Ticker led_ticker;


/*全局变量*/
volatile uint8_t nightled_flag = false;//WS2812BLED呼吸灯打开关闭标志
volatile uint8_t led_ctrl_idx = 0;//控制WS2812B的色彩
volatile uint8_t WS2812B_brightness = 125;//控制WS2812B的亮度

/*局部函数*/
void led_tick(void)
{
  if(nightled_flag == true)
  {
    WS2812B_Breathing(WS2812B_brightness);
  }
}

/*全局函数*/
void WS2812B_Init(void)
{
    FastLED.addLeds<LED_TYPE,LED_PIN,COLOR_ORDER>(leds,NUM_LEDS);

    FastLED.setBrightness(WS2812B_brightness);

    // fill_gradient_RGB(leds, 0, CRGB::Red, 29, CRGB::Yellow);
    // FastLED.show();


    led_ticker.attach_ms(60, led_tick);

    WS2812B_Close();
    //nightled_flag = true;//开启WS2812B灯带呼吸灯

    Serial.println("WS2812B Init success");
}

void WS2812B_SetGRB(uint8_t R, uint8_t G, uint8_t B)
{
    CRGB myRGBcolor(R,G,B);

    fill_solid(leds,NUM_LEDS,myRGBcolor);
    FastLED.show();

    Serial.printf("WS2812B_SetGRB,ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
}

// void WS2812B_Open(void)
// {
//     fill_solid(leds,NUM_LEDS,CRGB::Red);
//     FastLED.show();

//     Serial.printf("WS2812B Open success,ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
// }

void WS2812B_Close(void)
{
    fill_solid(leds,NUM_LEDS,CRGB::Black);
    FastLED.show();
    Serial.printf("WS2812B Close success,ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
}

void WS2812B_Breathing(uint8_t WS2812B_brightness)
{
    // if(nightled_flag == true)
    // {
        
    // }
    static uint8_t idx = 0;
    fill_palette(leds, NUM_LEDS, idx, 8, RainbowColors_p, WS2812B_brightness, LINEARBLEND);
    FastLED.show();

    idx++;
}

void WS2812B_SetBrightness(uint8_t brightness)
{
  WS2812B_brightness = brightness;

  //Serial.println(WS2812B_brightness);

  FastLED.setBrightness(WS2812B_brightness);

  FastLED.show();
}